package com.hkbigdata.sybx.controller;

import com.hkbigdata.sybx.bean.UserRegedit;
import com.hkbigdata.sybx.controller.ResponseResult;
import com.hkbigdata.sybx.service.UserRegeditService;
import com.hkbigdata.sybx.utils.Argon2Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/userRegedit")
public class UserRegeditController {

    @Autowired
    private UserRegeditService userRegeditService;

    // 查询所有用户
    @GetMapping("/all")
    public List<UserRegedit> getAllUsers() {
        return userRegeditService.getAllUsers();
    }

    // 登录接口
    @PostMapping("/login")
    public ResponseResult login(@RequestBody UserRegedit userRegedit) {
        try {
            System.out.println("登录请求 - 用户ID: " + userRegedit.getUser_id());

            if (userRegedit.getUser_id() == null || userRegedit.getUser_id().isEmpty()) {
                return ResponseResult.error(400, "账号不能为空");
            }
            if (userRegedit.getPassword_hash() == null || userRegedit.getPassword_hash().isEmpty()) {
                return ResponseResult.error(400, "密码不能为空");
            }

            UserRegedit dbUser = userRegeditService.getUserById(userRegedit.getUser_id());
            System.out.println("数据库用户信息: " + (dbUser != null ? "存在" : "不存在"));

            if (dbUser != null) {
                System.out.println("数据库中的密码哈希: " + dbUser.getPassword_hash());
                System.out.println("登录时使用的密码: " + userRegedit.getPassword_hash());

                // 使用Argon2验证密码
                boolean passwordValid = Argon2Util.verify(
                        dbUser.getPassword_hash(),
                        userRegedit.getPassword_hash()
                );
                System.out.println("密码验证结果: " + (passwordValid ? "成功" : "失败"));

                if (passwordValid) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("user", dbUser);
                    return ResponseResult.success("登录成功", data);
                }
            }
            return ResponseResult.error(401, "账号或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("登录异常: " + e.getMessage());
            return ResponseResult.error(500, "登录异常，请重试");
        }
    }

    // 注册接口
    @PostMapping("/register")
    public ResponseResult register(@RequestBody UserRegedit userRegedit) {
        try {
            // 参数校验
            if (userRegedit.getUser_id() == null || userRegedit.getUser_id().isEmpty()) {
                return ResponseResult.error(400, "账号不能为空");
            }
            if (userRegedit.getPassword_hash() == null || userRegedit.getPassword_hash().isEmpty()) {
                return ResponseResult.error(400, "密码不能为空");
            }

            // 检查用户是否已存在
            UserRegedit existingUser = userRegeditService.getUserById(userRegedit.getUser_id());
            if (existingUser != null) {
                return ResponseResult.error(400, "该账号已被注册");
            }

            // Argon2加密密码
            String hashedPassword = Argon2Util.hash(userRegedit.getPassword_hash());
            userRegedit.setPassword_hash(hashedPassword);

            // 执行注册
            int rows = userRegeditService.addUser(userRegedit);
            if (rows > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("user_id", userRegedit.getUser_id());
                return ResponseResult.success("注册成功", data);
            } else {
                return ResponseResult.error(400, "注册失败，请稍后再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(500, "注册异常，请重试");
        }
    }

    // 更新用户信息
    @PutMapping("/{user_id}")
    public ResponseResult updateUser(@PathVariable String user_id, @RequestBody UserRegedit userRegedit) {
        try {
            // 检查用户是否存在
            UserRegedit existingUser = userRegeditService.getUserById(user_id);
            if (existingUser == null) {
                return ResponseResult.error(404, "用户不存在");
            }

            // 设置要更新的用户ID
            userRegedit.setUser_id(user_id);

            // 如果更新了密码，进行加密
            if (userRegedit.getPassword_hash() != null && !userRegedit.getPassword_hash().isEmpty()) {
                String hashedPassword = Argon2Util.hash(userRegedit.getPassword_hash());
                userRegedit.setPassword_hash(hashedPassword);
            } else {
                // 保留原密码 - 不更新密码字段
                userRegedit.setPassword_hash(null);
            }

            // 执行更新
            System.out.println("updateUser 请求体: " + userRegedit);
            int rows = userRegeditService.updateUser(userRegedit);
            if (rows > 0) {
                return ResponseResult.success("更新成功");
            } else {
                return ResponseResult.error(400, "更新失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseResult.error(400, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(500, "更新异常，请重试");
        }
    }

    // 删除用户
    @DeleteMapping("/{user_id}")
    public ResponseResult deleteUser(@PathVariable String user_id) {
        try {
            // 检查用户是否存在
            UserRegedit existingUser = userRegeditService.getUserById(user_id);
            if (existingUser == null) {
                return ResponseResult.error(404, "用户不存在");
            }

            // 执行删除
            int rows = userRegeditService.deleteUser(user_id);
            if (rows > 0) {
                return ResponseResult.success("删除成功");
            } else {
                return ResponseResult.error(400, "删除失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseResult.error(400, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(500, "删除异常，请重试");
        }
    }

    // 密码更新请求DTO
    static class PasswordUpdateRequest {
        private String oldPassword;
        private String newPassword;

        public String getOldPassword() {
            return oldPassword;
        }

        public void setOldPassword(String oldPassword) {
            this.oldPassword = oldPassword;
        }

        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
}